package cn.com.yusys.yusp.admin.web.rest;

import cn.com.yusys.yusp.admin.Utils.IDUtils;
import cn.com.yusys.yusp.admin.service.CustCenterService;
import cn.com.yusys.yusp.commons.mapper.QueryModel;
import cn.com.yusys.yusp.commons.web.rest.dto.ResultDto;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;

@RestController
@RequestMapping("/api/CustCenter")
public class CustCenterResource {

    @Resource
    private CustCenterService custCenterService;



    //等级最高的两个进入之后，level为0的直接查询全部，level为1的查询所属的所有分行
    @GetMapping("/getGridName")
    public ResultDto<List<Map<String, Object>>> getGridName(QueryModel queryModel){
        String roleId= (String) queryModel.getCondition().get("roleId");
        String orgId = (String)queryModel.getCondition().get("orgId");
        List<Map<String, Object>> list =new ArrayList<>();
        if (orgId.equals("070667XN0") || orgId.equals("070667XN1") ||orgId.equals("070667860") ||orgId.equals("070667XN3")){
            queryModel.getCondition().put("roleLevel", "1");
            list = custCenterService.getGridName(queryModel);
            return new ResultDto<>(list);
        }
        if (roleId.equals("R0001") || roleId.equals("R0002") || roleId.equals("R0009")){
            queryModel.getCondition().put("roleLevel", "2");
            list = custCenterService.getGridName(queryModel);
        }
        //查询所有用户
        if (roleId.equals("R0008") || roleId.equals("R0007") || roleId.equals("R001")){
            queryModel.getCondition().put("roleLevel", "0");
            list = custCenterService.getGridName(queryModel);
        }
        //查询支行下所属的所有客户经理的用户 Sub-branch Manager
        if (roleId.equals("R0006") || roleId.equals("R0005") || roleId.equals("R0003") || roleId.equals("R0004")){
            queryModel.getCondition().put("roleLevel", "3");
            list = custCenterService.getGridName(queryModel);
        }
        return new ResultDto<>(list);
    }

    //等级最高的两个进入之后，level为0的直接查询全部，level为1的查询所属的所有分行
    @GetMapping("/getOrgName")
    public ResultDto<List<Map<String, Object>>> getOrgName(QueryModel queryModel){
        String roleId= (String) queryModel.getCondition().get("roleId");
        String orgId = (String)queryModel.getCondition().get("orgId");
        List<Map<String, Object>> list =new ArrayList<>();
        if (orgId.equals("070667XN0") || orgId.equals("070667XN1") ||orgId.equals("070667860") ||orgId.equals("070667XN3")){
            queryModel.getCondition().put("roleLevel", "1");
            list = custCenterService.getOrgName(queryModel);
            return new ResultDto<>(list);
        }
        if (roleId.equals("R0001") || roleId.equals("R0002") || roleId.equals("R0009")){
            queryModel.getCondition().put("roleLevel", "2");
            list = custCenterService.getOrgName(queryModel);
        }
        //查询所有用户
        if (roleId.equals("R0008") || roleId.equals("R0007") || roleId.equals("R001")){
            queryModel.getCondition().put("roleLevel", "0");
            list = custCenterService.getOrgName(queryModel);
        }
        //查询支行下所属的所有客户经理的用户 Sub-branch Manager
        if (roleId.equals("R0006") || roleId.equals("R0005") || roleId.equals("R0003") || roleId.equals("R0004")){
            queryModel.getCondition().put("roleLevel", "3");
            list = custCenterService.getOrgName(queryModel);
        }
        return new ResultDto<>(list);
    }

    @GetMapping("/getSecondGridName")
    public ResultDto<List<Map<String, Object>>> getSecondGridName(QueryModel queryModel){
        String roleId= (String) queryModel.getCondition().get("roleId");
        String orgId = (String)queryModel.getCondition().get("orgId");
        List<Map<String, Object>> list =new ArrayList<>();
        if (orgId.equals("070667XN0") || orgId.equals("070667XN1") ||orgId.equals("070667860") ||orgId.equals("070667XN3")){
            queryModel.getCondition().put("roleLevel", "1");
            list = custCenterService.getSecondGridName(queryModel);
            return new ResultDto<>(list);
        }
        if (roleId.equals("R0001") || roleId.equals("R0002") || roleId.equals("R0009")){
            queryModel.getCondition().put("roleLevel", "3");
        }
        //查询所有用户
        if (roleId.equals("R0008") || roleId.equals("R0007") || roleId.equals("R001")){
            queryModel.getCondition().put("roleLevel", "0");
        }
        //查询支行下所属的所有客户经理的用户 Sub-branch Manager
        if (roleId.equals("R0006") || roleId.equals("R0005") || roleId.equals("R0003") || roleId.equals("R0004")){
            queryModel.getCondition().put("roleLevel", "2");
        }
        list = custCenterService.getSecondGridName(queryModel);
        return new ResultDto<>(list);
    }

    //显示所有的客户信息,例如根据登录的用户id去查询此id属于哪一块,再根据用户信息表查询此人的级别，
    // 如果是最底层，就显示其归属网格的所有客户，如果是客户经理就显示该经理管辖下，所有业务员的客户
    @GetMapping("/getAllCustomerInformation")
    public ResultDto<List<Map<String, Object>>> getAllCustomerInformation(QueryModel queryModel){
        String roleId= (String) queryModel.getCondition().get("roleId");
        List<Map<String, Object>> list = new ArrayList<>();
        String orgId = (String)queryModel.getCondition().get("orgId");
        //如果orgId属于以上职业，则属于分行行长，显示分行下所有客户信息
        if (orgId.equals("070667XN0") || orgId.equals("070667XN1") ||orgId.equals("070667860") ||orgId.equals("070667XN3")){
            list = custCenterService.getBranchManagerInformation(queryModel);
            return new ResultDto<>(list);
        }
        //查询该客户经理所属的网格下的用户
        if (roleId.equals("R0001") || roleId.equals("R0002") || roleId.equals("R0009")){
            list = custCenterService.getCustomerManagerInformation(queryModel);
        }
        //查询所有用户
        if (roleId.equals("R0008") || roleId.equals("R0007") || roleId.equals("R001")){
            list = custCenterService.getAllCustomerInformation(queryModel);
        }
        //查询支行下所属的所有客户经理的用户 Sub-branch Manager
        if (roleId.equals("R0006") || roleId.equals("R0005") || roleId.equals("R0003") || roleId.equals("R0004")){
            list = custCenterService.getSubBranchManagerInformation(queryModel);
        }
        return new ResultDto<>(list);
    }

    @GetMapping("/updateCustomerImport")
    public ResultDto<Integer> updateCustomerImport(QueryModel queryModel){
        return new ResultDto<>(custCenterService.updateCustomerImport(queryModel));
    }

    @GetMapping("/addNewCustomer")
    public ResultDto<Integer> addNewCustomer(QueryModel queryModel) {
        queryModel.getCondition().put("custNo",IDUtils.getGuid());
        return  new ResultDto<>(custCenterService.addNewCustomer(queryModel));
    }

    @GetMapping("/updateCustomerInformation")
    public ResultDto<Integer> updateCustomerInformation(QueryModel queryModel){
        return new ResultDto<>(custCenterService.updateCustomerInformation(queryModel));
    }

    @GetMapping("/deleteCustomer")
    public ResultDto<Integer> deleteCustomer(QueryModel queryModel) {
        List<Integer> boardIdList = (List<Integer>)queryModel.getCondition().get("custNo");
        return new ResultDto<>(custCenterService.deleteCustomer(boardIdList));
    }

    @GetMapping("/getCustomerInformation")
    public ResultDto<List<Map<String, Object>>> getCustomerInformation(QueryModel queryModel){
        List<Map<String, Object>> list = custCenterService.getCustomerInformation(queryModel);
        return new ResultDto<>(list);
    }


    @GetMapping("/transferCustomer")
    public ResultDto<Object> transferCustomer(QueryModel queryModel){
        return custCenterService.transferCustomer(queryModel);
    }

    //上传excel，通过查询得知是否在表中存在重复，通过queryModel得知操作人员的id并记录
    //客户建档时候的插入
    @PostMapping("/uploadExcel")
    public ResultDto<Object> uploadExcel(@RequestParam("file") MultipartFile file, QueryModel queryModel) {
        XSSFWorkbook wb = null;
        ResultDto<Object> resultDto = new ResultDto<>();
        List<QueryModel> modelList = new ArrayList<>();
        List<String> ctfNoList = new ArrayList<>();
        if (file.isEmpty()) {
            resultDto.setCode(404);
            resultDto.setMessage("导入文件为空");
        }
        try {
            wb = new XSSFWorkbook(file.getInputStream());
            XSSFSheet sheet = wb.getSheetAt(0);
            int firstRowNum = sheet.getFirstRowNum();
            int lastRowNum = sheet.getLastRowNum();
            if (lastRowNum == 0) {
                resultDto.setMessage("未填写数据，请确认后导入");
                resultDto.setCode(401);
                return resultDto;
            }
            XSSFRow row = sheet.getRow(firstRowNum);
            short lastCellNum = sheet.getRow(0).getLastCellNum();
            //获得excel文件的列，与预先设计好的模板对比（模板为10列数据）
            if (lastCellNum != 10) {
                resultDto.setMessage("excel列数错误，请确定导入文件与模版一致");
                resultDto.setCode(401);
                return resultDto;
            }
            //依次获取表格内容，并检查是否为指定模板的内容
            if (!row.getCell(0).getStringCellValue().equals("客户名称")
            ) {
                resultDto.setMessage("第一列表头名称不是“客户名称”，请确定导入文件与模版一致。");
                resultDto.setCode(401);
                return resultDto;
            } else if (!row.getCell(1).getStringCellValue().equals("证件号码")) {
                resultDto.setMessage("第二列表头名称不是“证件号码”，请确定导入文件与模版一致。");
                resultDto.setCode(401);
                return resultDto;
            } else if (!row.getCell(2).getStringCellValue().equals("证件类型")) {
                resultDto.setMessage("第三列表头名称不是“证件类型”，请确定导入文件与模版一致。");
                resultDto.setCode(401);
                return resultDto;
            }else if (!row.getCell(3).getStringCellValue().equals("性别")) {
                resultDto.setMessage("第四列表头名称不是“性别”，请确定导入文件与模版一致。");
                resultDto.setCode(401);
                return resultDto;
            }else if (!row.getCell(4).getStringCellValue().equals("地址")) {
                resultDto.setMessage("第五列表头名称不是“地址”，请确定导入文件与模版一致。");
                resultDto.setCode(401);
                return resultDto;
            }else if (!row.getCell(5).getStringCellValue().equals("手机号码")) {
                resultDto.setMessage("第六表头名称不是“手机号码”，请确定导入文件与模版一致。");
                resultDto.setCode(401);
                return resultDto;
            }else if (!row.getCell(6).getStringCellValue().equals("场景类型")) {
                resultDto.setMessage("第七列表头名称不是“场景类型”，请确定导入文件与模版一致。");
                resultDto.setCode(401);
                return resultDto;
            }else if (!row.getCell(7).getStringCellValue().equals("栋/组")) {
                resultDto.setMessage("第八列表头名称不是“栋/组”，请确定导入文件与模版一致。");
                resultDto.setCode(401);
                return resultDto;
            }else if (!row.getCell(8).getStringCellValue().equals("行业")) {
                resultDto.setMessage("第九列表头名称不是“行业”，请确定导入文件与模版一致。");
                resultDto.setCode(401);
                return resultDto;
            }else if (!row.getCell(9).getStringCellValue().equals("职业")) {
                resultDto.setMessage("第十列表头名称不是“职业”，请确定导入文件与模版一致。");
                resultDto.setCode(401);
                return resultDto;
            }
            for (int i = firstRowNum + 1; i <= lastRowNum; i++) {
                //循环列表，获取每行
                XSSFRow rows = sheet.getRow(i);
                if (rows == null) {
                    resultDto.setMessage("第" + (i + 1) + "行数据为空");
                    resultDto.setCode(401);
                    return resultDto;
                }
                if (rows.getCell(0) == null) {
                    resultDto.setMessage("第" + (i + 1) + "行客户名称为空");
                    resultDto.setCode(401);
                    return resultDto;
                }
                if (rows.getCell(1) == null) {
                    resultDto.setMessage("第" + (i + 1) + "行证件号码为空");
                    resultDto.setCode(401);
                    return resultDto;
                }
                if (rows.getCell(2) == null) {
                    resultDto.setMessage("第" + (i + 1) + "行证件类型为空");
                    resultDto.setCode(401);
                    return resultDto;
                }if (rows.getCell(4) == null) {
                    resultDto.setMessage("第" + (i + 1) + "行地址为空");
                    resultDto.setCode(401);
                    return resultDto;
                }
                if (rows.getCell(5) == null) {
                    resultDto.setMessage("第" + (i + 1) + "行手机号码为空");
                    resultDto.setCode(401);
                    return resultDto;
                }if (rows.getCell(8) == null) {
                    resultDto.setMessage("第" + (i + 1) + "行行业为空");
                    resultDto.setCode(401);
                    return resultDto;
                }if (rows.getCell(9) == null) {
                    resultDto.setMessage("第" + (i + 1) + "行职业为空");
                    resultDto.setCode(401);
                    return resultDto;
                }
                QueryModel queryModel1 = new QueryModel();
                //检查行列为空
                if (rows.getCell(0).getStringCellValue().trim().equals("")) {
                    resultDto.setMessage("第" + (i + 1) + "行客户名称为空");
                    resultDto.setCode(401);
                    return resultDto;
                } else if (rows.getCell(1).getStringCellValue().trim().equals("")) {
                    resultDto.setMessage("第" + (i + 1) + "行证件号码为空");
                    resultDto.setCode(401);
                    return resultDto;
                } else if (rows.getCell(2).getStringCellValue().trim().equals("")) {
                    resultDto.setMessage("第" + (i + 1) + "行证件类型为空");
                    resultDto.setCode(401);
                    return resultDto;
                } else if (rows.getCell(4).getStringCellValue().trim().equals("")) {
                    resultDto.setMessage("第" + (i + 1) + "行地址为空");
                    resultDto.setCode(401);
                    return resultDto;
                } else if (rows.getCell(5).getStringCellValue().trim().equals("")) {
                    resultDto.setMessage("第" + (i + 1) + "行手机号码为空");
                    resultDto.setCode(401);
                    return resultDto;
                }else if (rows.getCell(8).getStringCellValue().trim().equals("")) {
                    resultDto.setMessage("第" + (i + 1) + "行行业为空");
                    resultDto.setCode(401);
                    return resultDto;
                } else if (rows.getCell(9).getStringCellValue().trim().equals("")) {
                    resultDto.setMessage("第" + (i + 1) + "行职业为空");
                    resultDto.setCode(401);
                    return resultDto;
                }
                //查询身份证号，是否唯一，如果不唯一，则返回特定行供用户更改
                queryModel1.getCondition().put("crtOprtrNo",queryModel.getCondition().get("userId") );
                queryModel1.getCondition().put("crtBrchNo",queryModel.getCondition().get("orgId") );
                queryModel1.getCondition().put("custName", rows.getCell(0).getStringCellValue());
                queryModel1.getCondition().put("ctfNo", rows.getCell(1).getStringCellValue());
                queryModel1.getCondition().put("ctfTp", rows.getCell(2).getStringCellValue());
                //性别代码部分进行查询
                queryModel1.getCondition().put("gndrCd", rows.getCell(3) == null ? null : rows.getCell(3).getStringCellValue());
                queryModel1.getCondition().put("address", rows.getCell(4).getStringCellValue());
                queryModel1.getCondition().put("mobNo", rows.getCell(5).getStringCellValue());
                //场景类型根据名称去查询
                queryModel1.getCondition().put("sceneType", rows.getCell(6) == null ? null :rows.getCell(6).getStringCellValue());
                queryModel1.getCondition().put("witchUnit", rows.getCell(7) == null ? null :rows.getCell(7).getStringCellValue());
                //企业行业类别的时候根据名称去查询对应id并存储
                queryModel1.getCondition().put("entpIdyCgy", rows.getCell(8).getStringCellValue());
                //职业类别的时候根据名称去查询对应id并存储
                queryModel1.getCondition().put("ocpCd", rows.getCell(9).getStringCellValue());
                queryModel1.getCondition().put("custNo", IDUtils.getGuid());
                ctfNoList.add(rows.getCell(1).getStringCellValue());
                modelList.add(queryModel1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //通过证件号码搜索已经存在的用户
        List<String> existCustList = custCenterService.selectExistCustInfo(ctfNoList);
        if (existCustList.size()==0) {
            custCenterService.excelAddNewCustomer(modelList);
            resultDto.setCode(200);
            resultDto.setMessage("导入成功");
        }
        else if (existCustList.size() == modelList.size()){
            resultDto.setCode(500);
            resultDto.setMessage("有0行数据成功导入，"+existCustList.size()+"行数据已经存在，请重新检查");
        }
        else {
            //如果查询的结果中有一部分是重复的，将重复的删除，将余下的部分给导入
            Iterator<QueryModel> iterator =modelList.iterator();
                while (iterator.hasNext()){
                    String ctfNo = (String) iterator.next().getCondition().get("ctfNo");
                    for (String str : existCustList){
                    if (ctfNo.equals(str)){
                        iterator.remove();
                    }
                }
            }
            custCenterService.excelAddNewCustomer(modelList);
            resultDto.setMessage("有"+modelList.size()+"行数据成功导入，"+existCustList.size()+"行数据已经存在，请重新检查");
            resultDto.setCode(500);
        }
        return resultDto;
    }

    public static QueryModel judgeUserJurisdiction(QueryModel queryModel,Boolean isStatisType){
        String roleId= (String) queryModel.getCondition().get("roleId");
        String orgId = (String)queryModel.getCondition().get("orgId");
        //如果orgId属于以上职业，则属于分行行长，显示下属所有支行的内容
        if (orgId.equals("070667XN0") || orgId.equals("070667XN1") ||orgId.equals("070667860") ||orgId.equals("070667XN3")){
            queryModel.getCondition().put("roleLevel", "1");
            if (isStatisType){
                queryModel.getCondition().put("statisType", "01");
            }
            return queryModel;
        }
        //查询该客户经理所能看到的内容
        if (roleId.equals("R0001") || roleId.equals("R0002") || roleId.equals("R0009")){
            queryModel.getCondition().put("roleLevel", "3");
            if (isStatisType){
                queryModel.getCondition().put("statisType", "03");
            }
        }
        //查询所有用户
        if (roleId.equals("R0008") || roleId.equals("R0007") || roleId.equals("R001")){
            if (isStatisType){
                queryModel.getCondition().put("statisType", "03");
            }
        }
        //查询支行下所属的所有支行行长的用户 Sub-branch Manager
        if (roleId.equals("R0006") || roleId.equals("R0005") || roleId.equals("R0003") || roleId.equals("R0004")){
            queryModel.getCondition().put("roleLevel", "2");
            if (isStatisType){
                queryModel.getCondition().put("statisType", "03");
            }
        }
        return queryModel;
    }

}
